[[...path]].page.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import {
  8. NextPage, GetServerSideProps, GetServerSidePropsContext,
  9. } from 'next';
  10. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  11. import dynamic from 'next/dynamic';
  12. import Head from 'next/head';
  13. import { useRouter } from 'next/router';
  14. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  15. // import { PageComments } from '~/components/PageComment/PageComments';
  16. // import { useTranslation } from '~/i18n';
  17. import { CrowiRequest } from '~/interfaces/crowi-request';
  18. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  19. // import { useIndentSize } from '~/stores/editor';
  20. // import { useRendererSettings } from '~/stores/renderer';
  21. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  22. import { CustomWindow } from '~/interfaces/global';
  23. import { RendererConfig } from '~/interfaces/services/renderer';
  24. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  25. import { PageModel, PageDocument } from '~/server/models/page';
  26. import UserUISettings, { UserUISettingsDocument } from '~/server/models/user-ui-settings';
  27. import Xss from '~/services/xss';
  28. import { useSWRxCurrentPage, useSWRxPageInfo, useSWRxPage } from '~/stores/page';
  29. import {
  30. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  31. } from '~/stores/ui';
  32. import loggerFactory from '~/utils/logger';
  33. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  34. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  35. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  36. import { BasicLayout } from '../components/Layout/BasicLayout';
  37. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  38. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  39. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  40. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  41. import {
  42. useCurrentUser, useCurrentPagePath,
  43. useIsLatestRevision,
  44. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  45. useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification, useIsIdenticalPath,
  46. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  47. useHackmdUri,
  48. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  49. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  50. useIsSlackConfigured, useIsBlinkedHeaderAtBoot, useRendererConfig,
  51. } from '../stores/context';
  52. import { useXss } from '../stores/xss';
  53. import {
  54. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  55. } from './commons';
  56. // import { useCurrentPageSWR } from '../stores/page';
  57. const logger = loggerFactory('growi:pages:all');
  58. const {
  59. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  60. } = pagePathUtils;
  61. const { removeHeadingSlash } = pathUtils;
  62. const IdenticalPathPage = (): JSX.Element => {
  63. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  64. return <IdenticalPathPage />;
  65. };
  66. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision, IPageInfoForEntity>;
  67. type Props = CommonProps & {
  68. currentUser: string,
  69. pageWithMetaStr: string,
  70. // pageUser?: any,
  71. // redirectTo?: string;
  72. // redirectFrom?: string;
  73. // shareLinkId?: string;
  74. isLatestRevision?: boolean
  75. isIdenticalPathPage?: boolean,
  76. isForbidden: boolean,
  77. isNotFound: boolean,
  78. IsNotCreatable: boolean,
  79. // isAbleToDeleteCompletely: boolean,
  80. isSearchServiceConfigured: boolean,
  81. isSearchServiceReachable: boolean,
  82. isSearchScopeChildrenAsDefault: boolean,
  83. isSlackConfigured: boolean,
  84. // isMailerSetup: boolean,
  85. isAclEnabled: boolean,
  86. // hasSlackConfig: boolean,
  87. // drawioUri: string,
  88. hackmdUri: string,
  89. // mathJax: string,
  90. // noCdn: string,
  91. // highlightJsStyle: string,
  92. // isAllReplyShown: boolean,
  93. // isContainerFluid: boolean,
  94. // editorConfig: any,
  95. isEnabledStaleNotification: boolean,
  96. // isEnabledLinebreaks: boolean,
  97. // isEnabledLinebreaksInComments: boolean,
  98. // adminPreferredIndentSize: number,
  99. // isIndentSizeForced: boolean,
  100. disableLinkSharing: boolean,
  101. rendererConfig: RendererConfig,
  102. // UI
  103. userUISettings: UserUISettingsDocument | null
  104. // Sidebar
  105. sidebarConfig: ISidebarConfig,
  106. };
  107. const GrowiPage: NextPage<Props> = (props: Props) => {
  108. // const { t } = useTranslation();
  109. const router = useRouter();
  110. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  111. const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
  112. // register global EventEmitter
  113. if (isClient()) {
  114. (window as CustomWindow).globalEmitter = new EventEmitter();
  115. }
  116. // commons
  117. useAppTitle(props.appTitle);
  118. useSiteUrl(props.siteUrl);
  119. useXss(new Xss());
  120. // useEditorConfig(props.editorConfig);
  121. useConfidential(props.confidential);
  122. useCsrfToken(props.csrfToken);
  123. // UserUISettings
  124. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  125. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  126. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  127. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  128. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  129. // page
  130. useCurrentPagePath(props.currentPathname);
  131. useIsLatestRevision(props.isLatestRevision);
  132. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  133. useIsForbidden(props.isForbidden);
  134. useIsNotFound(props.isNotFound);
  135. useIsNotCreatable(props.IsNotCreatable);
  136. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  137. // useShared();
  138. // useShareLinkId(props.shareLinkId);
  139. useIsSharedUser(false); // this page cann't be routed for '/share'
  140. useIsIdenticalPath(false); // TODO: need to initialize from props
  141. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  142. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  143. useIsBlinkedHeaderAtBoot(false);
  144. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  145. useIsSearchServiceReachable(props.isSearchServiceReachable);
  146. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  147. useIsSlackConfigured(props.isSlackConfigured);
  148. // useIsMailerSetup(props.isMailerSetup);
  149. useIsAclEnabled(props.isAclEnabled);
  150. // useHasSlackConfig(props.hasSlackConfig);
  151. // useDrawioUri(props.drawioUri);
  152. useHackmdUri(props.hackmdUri);
  153. // useMathJax(props.mathJax);
  154. // useNoCdn(props.noCdn);
  155. // useIndentSize(props.adminPreferredIndentSize);
  156. useDisableLinkSharing(props.disableLinkSharing);
  157. useRendererConfig(props.rendererConfig);
  158. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  159. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  160. // const { data: editorMode } = useEditorMode();
  161. let pageWithMeta: IPageToShowRevisionWithMeta | undefined;
  162. if (props.pageWithMetaStr != null) {
  163. pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageToShowRevisionWithMeta;
  164. }
  165. useCurrentPageId(pageWithMeta?.data._id);
  166. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  167. // useSWRxPage(pageWithMeta?.data._id);
  168. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  169. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  170. useIsUserPage(isUserPage(pageWithMeta?.data.path ?? ''));
  171. useIsNotCreatable(props.isForbidden || !isCreatablePage(pageWithMeta?.data.path ?? '')); // TODO: need to include props.isIdentical
  172. useCurrentPagePath(pageWithMeta?.data.path);
  173. useCurrentPathname(props.currentPathname);
  174. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  175. useEffect(() => {
  176. if (isClient() && window.location.pathname !== props.currentPathname) {
  177. router.replace(props.currentPathname, undefined, { shallow: true });
  178. }
  179. }, [props.currentPathname, router]);
  180. const classNames: string[] = [];
  181. // switch (editorMode) {
  182. // case EditorMode.Editor:
  183. // classNames.push('on-edit', 'builtin-editor');
  184. // break;
  185. // case EditorMode.HackMD:
  186. // classNames.push('on-edit', 'hackmd');
  187. // break;
  188. // }
  189. // if (props.isContainerFluid) {
  190. // classNames.push('growi-layout-fluid');
  191. // }
  192. // if (page == null) {
  193. // classNames.push('not-found-page');
  194. // }
  195. return (
  196. <>
  197. <Head>
  198. {/*
  199. {renderScriptTagByName('drawio-viewer')}
  200. {renderScriptTagByName('mathjax')}
  201. {renderScriptTagByName('highlight-addons')}
  202. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  203. */}
  204. </Head>
  205. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  206. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  207. <header className="py-0">
  208. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  209. </header>
  210. <div className="d-edit-none">
  211. {/* <GrowiSubNavigationSwitcher /> */}
  212. GrowiSubNavigationSwitcher
  213. </div>
  214. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  215. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  216. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  217. <div id="content-main" className="content-main grw-container-convertible">
  218. <div className="row">
  219. <div className="col">
  220. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  221. { !props.isIdenticalPathPage && (
  222. <>
  223. <PageAlerts />
  224. { props.isForbidden
  225. ? <>ForbiddenPage</>
  226. : <DisplaySwitcher />
  227. }
  228. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  229. {/* <PageStatusAlert /> */}
  230. PageStatusAlert
  231. </>
  232. ) }
  233. </div>
  234. </div>
  235. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  236. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  237. <div id="revision-toc-content" className="revision-toc-content"></div>
  238. </div>
  239. </div> */}
  240. </div>
  241. </div>
  242. <footer>
  243. {/* <PageComments /> */}
  244. PageComments
  245. </footer>
  246. <UnsavedAlertDialog />
  247. </BasicLayout>
  248. </>
  249. );
  250. };
  251. function getPageIdFromPathname(currentPathname: string): string | null {
  252. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  253. }
  254. class MultiplePagesHitsError extends ExtensibleCustomError {
  255. pagePath: string;
  256. constructor(pagePath: string) {
  257. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  258. this.pagePath = pagePath;
  259. }
  260. }
  261. async function getPageData(context: GetServerSidePropsContext, props: Props): Promise<IPageToShowRevisionWithMeta|null> {
  262. const req: CrowiRequest = context.req as CrowiRequest;
  263. const { crowi } = req;
  264. const { revisionId } = req.query;
  265. const Page = crowi.model('Page') as PageModel;
  266. const { pageService } = crowi;
  267. const { currentPathname } = props;
  268. const pageId = getPageIdFromPathname(currentPathname);
  269. const isPermalink = _isPermalink(currentPathname);
  270. const { user } = req;
  271. // check whether the specified page path hits to multiple pages
  272. if (!isPermalink) {
  273. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  274. if (count > 1) {
  275. throw new MultiplePagesHitsError(currentPathname);
  276. }
  277. }
  278. const result: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  279. const page = result?.data as unknown as PageDocument;
  280. // populate & check if the revision is latest
  281. if (page != null) {
  282. page.initLatestRevisionField(revisionId);
  283. await page.populateDataToShowRevision();
  284. props.isLatestRevision = page.isLatestRevision();
  285. }
  286. return result;
  287. }
  288. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props, pageWithMeta: IPageToShowRevisionWithMeta|null): Promise<void> {
  289. const req: CrowiRequest = context.req as CrowiRequest;
  290. const { crowi } = req;
  291. const Page = crowi.model('Page') as PageModel;
  292. const { currentPathname } = props;
  293. const pageId = getPageIdFromPathname(currentPathname);
  294. const isPermalink = _isPermalink(currentPathname);
  295. const page = pageWithMeta?.data;
  296. if (props.isIdenticalPathPage) {
  297. // TBD
  298. }
  299. else if (page == null) {
  300. props.isNotFound = true;
  301. props.IsNotCreatable = !isCreatablePage(currentPathname);
  302. // check the page is forbidden or just does not exist.
  303. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  304. props.isForbidden = count > 0;
  305. }
  306. else {
  307. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  308. if (isPermalink && page.isEmpty) {
  309. props.currentPathname = page.path;
  310. }
  311. // /path/to/page ==> /62a88db47fed8b2d94f30000
  312. if (!isPermalink && !page.isEmpty) {
  313. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  314. if (!isToppage) {
  315. props.currentPathname = `/${page._id}`;
  316. }
  317. }
  318. }
  319. }
  320. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  321. // const req: CrowiRequest = context.req as CrowiRequest;
  322. // const { crowi } = req;
  323. // const UserModel = crowi.model('User');
  324. // if (isUserPage(props.currentPagePath)) {
  325. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  326. // if (user != null) {
  327. // props.pageUser = JSON.stringify(user.toObject());
  328. // }
  329. // }
  330. // }
  331. async function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): Promise<void> {
  332. const req: CrowiRequest = context.req as CrowiRequest;
  333. const { crowi } = req;
  334. const {
  335. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  336. } = crowi;
  337. props.isSearchServiceConfigured = searchService.isConfigured;
  338. props.isSearchServiceReachable = searchService.isReachable;
  339. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  340. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  341. // props.isMailerSetup = mailService.isMailerSetup;
  342. props.isAclEnabled = aclService.isAclEnabled();
  343. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  344. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  345. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  346. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  347. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  348. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  349. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  350. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  351. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  352. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  353. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  354. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  355. // props.editorConfig = {
  356. // upload: {
  357. // image: crowi.fileUploadService.getIsUploadable(),
  358. // file: crowi.fileUploadService.getFileUploadEnabled(),
  359. // },
  360. // };
  361. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  362. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  363. props.rendererConfig = {
  364. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  365. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  366. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  367. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  368. plantumlUri: process.env.PLANTUML_URI ?? null,
  369. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  370. // XSS Options
  371. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  372. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  373. tagWhiteList: crowi.xssService.getTagWhiteList(),
  374. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  375. };
  376. props.sidebarConfig = {
  377. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  378. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  379. };
  380. }
  381. /**
  382. * for Server Side Translations
  383. * @param context
  384. * @param props
  385. * @param namespacesRequired
  386. */
  387. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  388. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  389. props._nextI18Next = nextI18NextConfig._nextI18Next;
  390. }
  391. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  392. const req: CrowiRequest = context.req as CrowiRequest;
  393. const { user } = req;
  394. const result = await getServerSideCommonProps(context);
  395. // check for presence
  396. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  397. if (!('props' in result)) {
  398. throw new Error('invalid getSSP result');
  399. }
  400. const props: Props = result.props as Props;
  401. let pageWithMeta;
  402. try {
  403. pageWithMeta = await getPageData(context, props);
  404. props.pageWithMetaStr = JSON.stringify(pageWithMeta);
  405. }
  406. catch (err) {
  407. if (err instanceof MultiplePagesHitsError) {
  408. props.isIdenticalPathPage = true;
  409. }
  410. else {
  411. throw err;
  412. }
  413. }
  414. injectRoutingInformation(context, props, pageWithMeta);
  415. injectServerConfigurations(context, props);
  416. injectNextI18NextConfigurations(context, props, ['translation']);
  417. if (user != null) {
  418. props.currentUser = JSON.stringify(user);
  419. }
  420. // UI
  421. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  422. props.userUISettings = JSON.parse(JSON.stringify(userUISettings));
  423. return {
  424. props,
  425. };
  426. };
  427. export default GrowiPage;